package com.misyi.designpattern.observer;

import org.openjdk.jol.vm.VM;

import java.util.Observable;
import java.util.Observer;

/**
 * 观察者模式
 *
 * @author licong
 * @date 2021-09-13 下午11:22
 */
public class ObServerPatternDemo {

    public static void main(String[] args) {
        Subject subject = new Subject();
        Observer observer = new ConcreateObserver();
        subject.addObserver(observer);

        subject.setState(1);
        System.out.println(VM.current().addressOf(subject.getState()));
    }

    public static class Subject extends Observable {

        private Integer state = 0;

        public Integer getState() {
            return state;
        }

        public void setState(Integer state) {
            // 状态改变时, 通知观察者
            this.state = state;
            // 这里设置状态改变了, 需要通知观察者
            this.setChanged();
            // 第一种方式, 推送
//            this.notifyObservers(state);
            // 第二种方式, 拉取
            this.notifyObservers();
        }
    }

    public static class ConcreateObserver implements Observer {


        @Override
        public void update(Observable o, Object arg) {
            // o 为拉取, arg 为推送的数据
            Subject subject = (Subject)o;
            Integer state = subject.getState();
            System.out.println("观察到了状态的改变, 值为" + state);
        }
    }

}
